<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
        offset="50"
      >
        <!-- item 是要传入item项的props接收 -->
        <ArticleItem
          v-for="item in ArticleList"
          :key="item.art_id"
          :item="item"
          :isShow="true"
          @disLikeEV="disLikeEV"
          @reports="reports"
          @click.native="toArticleDetail(item.art_id)"
        >
        </ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import ArticleItem from '../../../components/ArticleItem.vue'
import {
  getArticleListAPI,
  articleDislikeAPI,
  articleReportAPI
} from '@/api/index.js'
import { timeAgo } from '@/utils/date'
import Notify from '@/ui/Notify.js'
export default {
  components: {
    ArticleItem
  },
  props: {
    channelId: Number
  },
  data() {
    return {
      ArticleList: [],
      loading: false,
      finished: false,
      nextTime: new Date().getTime(), // 用于加载更多(分页)
      isLoading: false
    }
  },
  created() {
    this.getArticleList()
  },
  methods: {
    // 注册dayjs方法
    timeAgo: timeAgo,
    // 获取文章列表数据
    async getArticleList() {
      const { data: res } = await getArticleListAPI({
        channelId: this.channelId,
        timestamp: this.nextTime
      })
      this.ArticleList = [...this.ArticleList, ...res.data.results]
      this.nextTime = res.data.pre_timestamp

      // 如果不关闭,底部一直是加载中状态,下次触底会再触发onLoad
      this.loading = false

      // 本次返回的数据的最后的，没有数据了
      if (this.ArticleList.pre_timestamp === null) {
        this.finished = true
      }

      // 下拉刷新完请求，就关闭
      this.isLoading = false
    },
    async onLoad() {
      if (this.ArticleList.length === 0) {
        return
      }
      this.getArticleList()
    },
    // 下拉刷新
    onRefresh() {
      setTimeout(() => {
        this.ArticleList = []
        this.nextTime = new Date().getTime()
        this.getArticleList()
      }, 2000)
    },
    // 反馈 - 不感兴趣
    async disLikeEV(id) {
      await articleDislikeAPI(id)
      Notify({ type: 'success', message: '反馈成功' })
    },
    async reports(item, type) {
      try {
        await articleReportAPI({
          target: item.art_id,
          type: type,
          remark: '其他问题'
        })
        Notify({ type: 'success', message: '举报成功！' })
      } catch (error) {
        Notify({ type: 'warning', message: '举报失败' })
      }
    },
    // 首页文章详情
    toArticleDetail(id) {
      this.$router.push({
        path: `/detail?art_id=${id}`
      })
    }
  }
}
</script>
<style lang="less" scoped></style>
